/*
 * Copyright (c) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the 'License');
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an 'AS IS' BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

'use strict'

/**
 * Module dependencies.
 * @private
 */

var db = require('mime-db')

/**
 * Module variables.
 * @private
 */


/**
 * Module exports.
 * @public
 */

exports.extensions = Object.create(null)
exports.lookup = lookup
exports.types = Object.create(null)

// Populate the extensions/types maps
populateMaps(exports.extensions, exports.types)



let splitDeviceRe =
    /^([a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/]+[^\\\/]+)?([\\\/])?([\s\S]*?)$/;

let splitTailRe =
    /^([\s\S]*?)((?:\.{1,2}|[^\\\/]+?|)(\.[^.\/\\]*|))(?:[\\\/]*)$/;

let win32 = {};

function splitPath(filename) {
    var result = splitDeviceRe.exec(filename),
        device = (result[1] || '') + (result[2] || ''),
        tail = result[3] || '';
    var result2 = splitTailRe.exec(tail),
        dir = result2[1],
        basename = result2[2],
        ext = result2[3];
    return [device, dir, basename, ext];
}
win32.extname = function(path) {
    return splitPath(path)[3];
};

/**
 * Lookup the MIME type for a file path/extension.
 *
 * @param {string} path
 * @return {boolean|string}
 */
function lookup (path) {
    if (!path || typeof path !== 'string') {
        return false
    }

    var extension = win32.extname('x.' + path)
        .toLowerCase()
        .substr(1)
    if (!extension) {
        return false
    }
    return exports.types[extension] || false
}

/**
 * Populate the extensions and types maps.
 * @private
 */

function populateMaps (extensions, types) {
    var preference = ['nginx', 'apache', undefined, 'iana']

    Object.keys(db).forEach(function forEachMimeType (type) {
        var mime = db[type]
        var exts = mime.extensions

        if (!exts || !exts.length) {
            return
        }

        extensions[type] = exts

        for (var i = 0; i < exts.length; i++) {
            var extension = exts[i]

            if (types[extension]) {
                var from = preference.indexOf(db[types[extension]].source)
                var to = preference.indexOf(mime.source)
                if (types[extension] !== 'application/octet-stream' &&
                    (from > to || (from === to && types[extension].substr(0, 12) === 'application/'))) {
                    return ;
                }
            }

            types[extension] = type
        }
    })
}
